package com.skcc.ts.nsi.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.util.Log;

public class SocketHandler {

	public static String[] communicate(String Command[], String addr, String port) {
		String[] cmd = null;
		String[] data = null;
		cmd = Command;
		data = new String[Command.length];
		String login_addr = addr;
		int login_port = Integer.parseInt(port);

		try {
			// Socket sock = new Socket("10.250.115.81", 10001);
			// Socket sock = new Socket("10.250.112.82", 10001);

			Socket sock = new Socket(login_addr, login_port);
			
			OutputStream out = sock.getOutputStream();
			InputStream in = sock.getInputStream();
			PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "ms949"));
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "ms949"));
			for (int i = 0; i < cmd.length; i++) {
				pw.println(cmd[i]);
				pw.flush();
				data[i] = br.readLine();
				while (true) {
					if (data[i] != null) {
						break;
					}
					try {
						Thread.sleep(500);
						Log.d("waiting", "...");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			sock.close();

		} catch (UnknownHostException Ue) {
			// TODO Auto-generated catch block
			Ue.printStackTrace();
		} catch (IOException Ie) {
			// TODO Auto-generated catch block
			Ie.printStackTrace();
		}
		return data;
	}// end of communicate

}
